<template>
  <div class="goods-management-container">
    <!-- 搜索和操作区域 -->
    <div class="search-operation-area">
      <el-form
        :inline="true"
        :model="searchForm"
        class="search-form"
      >
        <el-form-item label="商品ID">
          <el-input
            v-model="searchForm.id"
            placeholder="输入商品ID"
            clearable
          />
        </el-form-item>
        <el-form-item label="商品名称">
          <el-input
            v-model="searchForm.name"
            placeholder="输入商品名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="商品类型">
          <el-select
            v-model="searchForm.type"
            placeholder="选择商品类型"
            clearable
          >
            <el-option
              label="鱼竿"
              value="鱼竿"
            />
            <el-option
              label="渔网"
              value="渔网"
            />
            <el-option
              label="鱼线"
              value="鱼线"
            />
            <el-option
              label="鱼饵"
              value="鱼饵"
            />
            <el-option
              label="配件"
              value="配件"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="handleSearch"
          >
            <i class="el-icon-search" /> 搜索
          </el-button>
          <el-button @click="resetSearch">
            <i class="el-icon-refresh" /> 重置
          </el-button>
          <el-button
            type="primary"
            @click="handleAdd"
          >
            <i class="el-icon-plus" /> 添加商品
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 商品表格 -->
    <el-table
      :data="tableData"
      border
      style="width: 100%; margin-top: 20px"
      :header-cell-style="{
        background: '#f5f7fa',
        color: '#606266',
        fontWeight: 'bold'
      }"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="selection"
        width="80"
        align="center"
      />
      <el-table-column
        prop="product.productId"
        label="ID"
        width="100"
        align="center"
      />
      <el-table-column
        label="商品图"
        width="120"
        align="center"
      >
        <template #default="{row}">
          <el-image
            style="width: 60px; height: 60px"
            :src="row.product.mainImage"
            fit="cover"
            :preview-src-list="row.product.mainImage ? [row.product.mainImage] : []"
          >
            <div
              v-if="!row.product.mainImage"
              class="image-slot"
            >
              <i class="el-icon-picture-outline" />
            </div>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column
        prop="product.title"
        label="商品名称"
        align="center"
      />
      <el-table-column
        prop="category.typeName"
        label="类型"
        width="150"
        align="center"
      >
        <template #default="{row}">
          <el-tag :type="getTagType(row.category.typeName)">
            {{ row.category.typeName }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="product.price"
        label="价格(元)"
        width="150"
        align="center"
      />
      <el-table-column
        prop="product.number"
        label="库存"
        width="150"
        align="center"
      />
      <el-table-column
        prop="status"
        label="状态"
        width="250"
        align="center"
      >
        <template #default="{row}">
          <el-switch
            v-model="row.product.status"
            :active-value="true"
            :inactive-value="false"
            active-color="#13ce66"
            inactive-color="#ff4949"
            @change="handleStatusChange(row)"
          />
          <span style="margin-left: 8px">
            {{ row.product.status ? '已上架' : '已下架' }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        width="200"
        align="center"
      >
        <template #default="{row}">
          <el-button
            size="mini"
            @click="handleEdit(row)"
          >
            编辑
          </el-button>
          <el-button
            size="mini"
            type="info"
            @click="handleDetail(row)"
          >
            详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="custom-pagination">
      <div class="pagination-content">
        <!-- 显示正确的总记录数 -->
        <span class="total-info">共 {{ pagination.total }} 条记录</span>

        <el-pagination
          :current-page.sync="pagination.currentPage"
          :page-size.sync="pagination.pageSize"
          :total="pagination.total"
          :page-count="pagination.totalPages"
          :page-sizes="[10, 20, 30]"
          layout="prev, pager, next, sizes"
          @current-change="fetchGoodsList"
          @size-change="handlePageSizeChange"
        />

        <div class="page-jump">
          <span>前往</span>
          <el-input
            v-model.number="jumpPage"
            size="mini"
            style="width: 60px"
            @keyup.enter.native="handleJumpPage"
          />
          <span>页</span>
        </div>
      </div>
    </div>

    <!-- 商品详情对话框 -->
    <el-dialog
      title="商品详情"
      :visible.sync="detailVisible"
      width="50%"
      :modal="false"
    >
      <div
        v-if="currentGoods"
        class="detail-content"
      >
        <el-descriptions
          :column="1"
          border
        >
          <el-descriptions-item label="商品ID">
            {{ currentGoods.product.productId }}
          </el-descriptions-item>
          <el-descriptions-item label="商品名称">
            {{ currentGoods.product.title }}
          </el-descriptions-item>
          <el-descriptions-item label="商品类型">
            <el-tag :type="getTagType(currentGoods.category.typeName)">
              {{ currentGoods.category.typeName }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="价格">
            {{ currentGoods.product.price }} 元
          </el-descriptions-item>
          <el-descriptions-item label="库存">
            {{ currentGoods.product.number }}
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="currentGoods.product.status ? 'success' : 'danger'">
              {{ currentGoods.product.status ? '已上架' : '已下架' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="商品图片">
            <el-image
              style="width: 200px; height: 200px"
              :src="currentGoods.product.mainImage"
              fit="cover"
              :preview-src-list="currentGoods.product.mainImage ? [currentGoods.product.mainImage] : []"
            >
              <div
                v-if="!currentGoods.product.mainImage"
                class="image-slot"
              >
                <i class="el-icon-picture-outline" /> 暂无图片
              </div>
            </el-image>
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>

    <!-- 添加/编辑商品对话框 -->
    <el-dialog
      :title="dialogMode === 'add' ? '添加商品' : '编辑商品'"
      :visible.sync="dialogVisible"
      width="600px"
      :modal="false"
    >
      <el-form
        ref="goodsForm"
        :model="currentForm"
        :rules="rules"
        label-width="100px"
      >
        <!-- 商品名称 -->
        <el-form-item
          label="商品名称"
          prop="name"
          required
        >
          <el-input
            v-model="currentForm.name"
            placeholder="请输入商品名称"
          />
          <div
            v-if="$refs.goodsForm && $refs.goodsForm.fields.name && $refs.goodsForm.fields.name.validateState === 'error'"
            class="el-form-item__error"
          >
            商品名称不能为空
          </div>
        </el-form-item>

        <!-- 商品图片 -->
        <el-form-item
          label="商品图片"
          prop="image"
        >
          <div class="image-upload-container">
            <div
              v-if="currentForm.image"
              class="image-preview"
            >
              <img
                :src="currentForm.image"
                class="preview-image"
              >
            </div>
            <div
              v-else
              class="upload-area"
              @click="triggerFileInput"
            >
              <i class="el-icon-plus" />
              <span>点击上传图片</span>
            </div>
            <input
              ref="fileInput"
              type="file"
              accept="image/*"
              style="display: none"
              @change="handleImageChange"
            >
            <div style="margin-top: 10px;">
              <el-button
                size="small"
                type="primary"
                @click="triggerFileInput"
              >
                {{ currentForm.image ? '更换图片' : '上传图片' }}
              </el-button>
              <el-button
                v-if="currentForm.image"
                size="small"
                type="danger"
                @click="removeImage"
              >
                删除图片
              </el-button>
            </div>
          </div>
        </el-form-item>

        <!-- 商品类型 -->
        <el-form-item
          label="商品类型"
          prop="type"
          required
        >
          <el-select
            v-model="currentForm.type"
            placeholder="请选择商品类型"
            style="width: 100%"
          >
            <el-option
              label="鱼竿"
              value="鱼竿"
            />
            <el-option
              label="渔网"
              value="渔网"
            />
            <el-option
              label="鱼线"
              value="鱼线"
            />
            <el-option
              label="鱼饵"
              value="鱼饵"
            />
            <el-option
              label="配件"
              value="配件"
            />
          </el-select>
        </el-form-item>

        <!-- 价格 -->
        <el-form-item
          label="价格"
          prop="price"
          required
        >
          <el-input-number
            v-model="currentForm.price"
            :min="0"
            :precision="2"
            controls-position="right"
            style="width: 100%"
          />
        </el-form-item>

        <!-- 库存 -->
        <el-form-item
          label="库存"
          prop="stock"
          required
        >
          <el-input-number
            v-model="currentForm.stock"
            :min="0"
            controls-position="right"
            style="width: 100%"
          />
        </el-form-item>

        <!-- 状态 -->
        <el-form-item
          label="状态"
          prop="status"
        >
          <el-radio-group v-model="currentForm.status">
            <el-radio label="上架">
              上架
            </el-radio>
            <el-radio label="下架">
              下架
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="dialogVisible = false">
          取 消
        </el-button>
        <el-button
          type="primary"
          @click="submitForm"
        >
          确 定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import $ from 'jquery'

export default {
  name: 'GoodsManagement',
  data () {
    return {
      loading: false,
      searchForm: {
        id: '',
        name: '',
        type: ''
      },
      tableData: [],
      selectedIds: [],
      allData: [], // 存储所有商品数据
      pagination: {
        currentPage: 1, // 当前页码
        pageSize: 10, // 每页条数
        total: 0, // 总记录数（初始值，实际从接口获取）
        totalPages: 10 // 总页数（初始值，实际从接口获取）
      },
      jumpPage: 1, // 跳页输入绑定
      dialogVisible: false,
      detailVisible: false,
      dialogMode: 'add',
      currentGoods: null,
      currentForm: {
        id: '',
        name: '',
        type: '鱼竿',
        specs: {},
        price: 0,
        stock: 0,
        sales: 0,
        scene: [],
        status: '上架',
        image: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择商品类型', trigger: 'change' }
        ],
        price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' },
          { type: 'number', message: '价格必须为数字值' }
        ],
        stock: [
          { required: true, message: '请输入库存数量', trigger: 'blur' },
          { type: 'integer', message: '库存必须为整数' }
        ]
      }
    }
  },
  created () {
    this.fetchGoodsList()
  },
  methods: {
    /**
     * 获取商品分页数据（修正版）
     */
    fetchGoodsList () {
      this.loading = true

      $.ajax({
        url: 'http://localhost:3000/api/product/findProductsByPage',
        type: 'GET',
        data: {
          page: this.pagination.currentPage,
          size: this.pagination.pageSize
        },
        success: (response) => {
          if (response.code === 200) {
            // 1. 处理表格数据
            this.tableData = response.data.list.map(item => ({
              ...item,
              product: {
                ...item.product,
                statusText: item.product.status ? '已上架' : '已下架',
                statusTag: item.product.status ? 'success' : 'danger',
                mainImage: item.product.mainImage
                  ? `http://localhost:3000/api/images/${item.product.mainImage}`
                  : ''
              }
            }))

            // 2. 关键修正：计算正确的总记录数
            const totalRecords = response.data.pages * this.pagination.pageSize

            // 3. 更新分页信息
            this.pagination = {
              currentPage: response.data.pageNum,
              pageSize: response.data.pageSize,
              total: totalRecords, // 显示总记录数100
              totalPages: response.data.pages // 总页数10
            }

            // 4. 同步跳页输入框
            this.jumpPage = this.pagination.currentPage
          }
        },
        error: (xhr) => {
          this.$message.error(`加载失败: ${xhr.statusText}`)
        },
        complete: () => {
          this.loading = false
        }
      })
    },
    // 搜索商品
    handleSearch () {
      this.pagination.currentPage = 1
      this.jumpPage = 1
      // 如果搜索表单中有名称字段，则调用名称搜索API
      if (this.searchForm.name) {
        this.loading = true
        $.ajax({
          url: 'http://localhost:3000/api/product/searchProductsByTitleWithPagination',
          type: 'GET',
          data: {
            title: this.searchForm.name,
            page: this.pagination.currentPage,
            size: this.pagination.pageSize
          },
          success: (response) => {
            if (response.code === 200) {
              this.tableData = response.data.list.map(item => ({
                ...item,
                product: {
                  ...item.product,
                  mainImage: item.product?.mainImage
                    ? `http://localhost:3000/api/images/${item.product.mainImage}`
                    : ''
                }
              }))
              this.pagination.total = response.data.total
            }
          },
          error: (xhr) => {
            this.$message.error(`搜索失败: ${xhr.statusText || '未知错误'}`)
          },
          complete: () => {
            this.loading = false
          }
        })
      } else {
        // 如果没有名称搜索条件，则调用普通分页查询
        this.fetchGoodsList()
      }
    },

    // 重置搜索
    resetSearch () {
      this.searchForm = {
        id: '',
        name: '',
        type: ''
      }
      this.pagination.currentPage = 1
      this.jumpPage = 1
      this.fetchGoodsList()
    },
    // 添加商品
    handleAdd () {
      this.dialogMode = 'add'
      this.currentForm = {
        id: '',
        name: '',
        type: '鱼竿',
        price: 0,
        stock: 0,
        status: '上架',
        image: ''
      }
      this.dialogVisible = true
    },

    // 编辑商品
    handleEdit (row) {
      this.dialogMode = 'edit'
      this.currentForm = {
        id: row.product.productId,
        name: row.product.title,
        type: this.getTypeByCategoryId(row.product.categoryId),
        price: row.product.price,
        stock: row.product.number,
        // 保持与表单一致使用字符串
        status: row.product.status ? '上架' : '下架',
        image: row.product.mainImage || ''
      }
      this.dialogVisible = true
    },

    // 添加这个方法
    getTypeByCategoryId (categoryId) {
      const idMap = {
        1: '鱼竿',
        2: '渔网',
        3: '鱼线',
        4: '鱼饵',
        5: '配件'
      }
      return idMap[categoryId] || '鱼竿'
    },

    // 触发文件选择
    triggerFileInput () {
      this.$refs.fileInput.click()
    },

    // 处理图片上传
    handleImageChange (e) {
      const file = e.target.files[0]
      if (!file) return

      const isImage = file.type.includes('image/')
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isImage) {
        this.$message.error('只能上传图片文件!')
        return
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
        return
      }

      this.currentForm.image = URL.createObjectURL(file)
      this.$refs.fileInput.value = ''
    },

    // 删除图片
    removeImage () {
      this.currentForm.image = ''
    },

    // 类型变化
    handleTypeChange (type) {
      this.currentForm.specs = this.getDefaultSpecs(type)
    },

    // 提交表单
    submitForm () {
      this.$refs.goodsForm.validate((valid) => {
        if (!valid) return false

        const formData = new FormData()
        const fileInput = this.$refs.fileInput

        if (fileInput.files.length > 0) {
          formData.append('image', fileInput.files[0])
        }

        // 使用const声明url变量
        const url = this.dialogMode === 'add'
          ? 'http://localhost:3000/api/product/addProduct'
          : 'http://localhost:3000/api/product/update'

        // 添加公共参数
        formData.append('title', this.currentForm.name)
        formData.append('price', this.currentForm.price)
        formData.append('number', this.currentForm.stock)

        if (this.dialogMode === 'add') {
          formData.append('categoryId', this.getCategoryIdByType(this.currentForm.type))
        } else {
          formData.append('productId', this.currentForm.id)
          formData.append('status', this.currentForm.status === '上架')
        }

        this.loading = true
        $.ajax({
          url,
          type: 'POST',
          data: formData,
          processData: false,
          contentType: false,
          success: (response) => {
            if (response.code === 200) {
              this.$message.success(this.dialogMode === 'add' ? '添加成功' : '更新成功')
              this.dialogVisible = false
              this.fetchGoodsList()
            } else {
              this.$message.error(response.message || '操作失败')
            }
          },
          error: (xhr) => {
            this.$message.error(`请求失败: ${xhr.statusText || '未知错误'}`)
          },
          complete: () => {
            this.loading = false
          }
        })
      })
    },

    handleDetail (row) {
      this.currentGoods = row
      this.detailVisible = true
    },

    // 状态变更
    handleStatusChange (row) {
      const newStatus = row.product.status // 直接使用当前值
      $.ajax({
        url: 'http://localhost:3000/api/product/update',
        type: 'POST',
        data: {
          productId: row.product.productId,
          status: newStatus
        },
        success: (response) => {
          if (response.code === 200) {
            this.$message.success(`商品已${newStatus ? '上架' : '下架'}`)
            // 不需要手动更新状态，因为v-model已经处理了
          } else {
            // 回滚状态
            row.product.status = !newStatus
            this.$message.error(response.message || '状态更新失败')
          }
        },
        error: (xhr) => {
          // 回滚状态
          row.product.status = !newStatus
          this.$message.error('请求失败: ' + xhr.statusText)
        }
      })
    },
    // 选择变化
    handleSelectionChange (val) {
      this.selectedIds = val.map(item => item.id)
    },

    /**
     * 当前页码变化
     */
    handleCurrentChange (newPage) {
      this.pagination.currentPage = newPage
      this.jumpPage = newPage
      this.fetchGoodsList()
    },

    /**
     * 每页条数变化（修正版）
     */
    handlePageSizeChange (newSize) {
      this.pagination.pageSize = newSize
      this.pagination.currentPage = 1

      // 重新计算总页数
      this.pagination.totalPages = Math.ceil(this.pagination.total / newSize)

      this.fetchGoodsList()
    },

    /**
     * 跳转到指定页
     */
    handleJumpPage () {
      const pageNum = parseInt(this.jumpPage)
      const maxPage = this.pagination.totalPages

      if (pageNum >= 1 && pageNum <= maxPage) {
        this.pagination.currentPage = pageNum
        this.fetchGoodsList()
      } else {
        this.$message.warning(`请输入1-${maxPage}之间的页码`)
        this.jumpPage = this.pagination.currentPage
      }
    },

    // 获取标签类型
    getTagType (type) {
      const map = {
        鱼竿: 'primary',
        渔网: 'success',
        鱼线: 'warning',
        鱼饵: 'danger',
        配件: 'info'
      }
      return map[type] || ''
    },

    // 获取默认规格
    getDefaultSpecs (type) {
      switch (type) {
      case '鱼竿': return { length: '', sections: '', action: '' }
      case '渔网': return { size: '', mesh: '' }
      case '鱼线': return { size: '', strength: '' }
      case '鱼饵': return { type: '', color: '' }
      case '配件': return { capacity: '', material: '' }
      default: return {}
      }
    }

  }
}
</script>

<style scoped>
.goods-management-container {
  padding: 20px;
  background-color: #f5f7fa;
}

.search-operation-area {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}

.goods-table {
  margin-bottom: 20px;
  background-color: #fff;
  padding: 15px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.pagination-area {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  margin-top: 20px;
}

.pagination-area .el-pagination {
  margin-left: 15px;
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
}

.image-slot i {
  font-size: 30px;
}

/* 表格单元格居中 */
.el-table >>> .el-table__cell {
  text-align: center;
  padding: 8px 0;
}

/* 操作按钮间距调整 */
.el-table >>> .cell .el-button {
  margin: 0 3px;
  padding: 5px 8px;
}

/* 确保表格填满容器 */
.el-table {
  width: 100% !important;
}

/* 上架/下架开关样式优化 */
.el-switch__label {
  position: absolute;
  display: none;
  color: #fff;
  font-size: 12px;
  width: 100%;
}
.el-switch__label--left {
  z-index: 9;
  left: 8px;
}
.el-switch__label--right {
  right: 8px;
}
.el-switch__label.is-active {
  display: block;
}
.el-switch .el-switch__core {
  width: 60px !important;
}

/* 详情内容样式 */
.detail-content {
  padding: 20px;
}

/* 无遮罩层对话框样式 */
.el-dialog__wrapper {
  background-color: transparent !important;
}
.el-dialog {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border-radius: 4px;
}

/* 图片上传容器样式 */
.image-upload-container {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.image-preview {
  width: 178px;
  height: 178px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  margin-bottom: 10px;
  overflow: hidden;
}

.preview-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.upload-area {
  width: 178px;
  height: 178px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: #8c939d;
  font-size: 14px;
  margin-bottom: 10px;
  cursor: pointer;
}

.upload-area i {
  font-size: 28px;
  margin-bottom: 5px;
}

.image-actions {
  display: flex;
  gap: 10px;
}

.pagination-area {
  margin-top: 20px;
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.pagination-area > span {
  margin-right: 15px;
}

.el-pagination {
  padding: 0;
}

.custom-pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-start; /* 改为flex-start让分页靠左 */
}

.pagination-content {
  display: flex;
  align-items: center;
}

.el-pagination {
  padding: 0;
}

/* 调整分页组件内部元素的间距 */
.el-pagination .btn-prev,
.el-pagination .btn-next,
.el-pagination .el-pager li {
  margin-right: 8px;
}
</style>
